#!/bin/bash

# MQTT客户端构建脚本
# 支持多平台交叉编译

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="$SCRIPT_DIR/build"

# 默认配置
TARGET_ARCH="native"
BUILD_TYPE="release"
STATIC_LINK="no"
VERBOSE="no"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    if [ "$VERBOSE" = "yes" ]; then
        echo -e "${BLUE}[DEBUG]${NC} $1"
    fi
}

# 显示帮助信息
show_help() {
    cat << EOF
MQTT客户端构建脚本

用法: $0 [选项]

选项:
    -a, --arch ARCH        目标架构: native, arm, aarch64, riscv64, mips (默认: native)
    -t, --type TYPE        构建类型: debug, release (默认: release)
    -s, --static           启用静态链接
    -v, --verbose          详细输出
    -c, --clean            清理构建目录
    -h, --help             显示此帮助信息

示例:
    $0                     # 本地编译
    $0 -a arm -s           # ARM交叉编译，静态链接
    $0 -a aarch64 -t debug # ARM64交叉编译，调试版本
    $0 -c                  # 清理构建

支持的架构和对应的交叉编译器:
    native   : gcc (本地编译)
    arm      : arm-linux-gnueabihf-gcc
    aarch64  : aarch64-linux-gnu-gcc
    riscv64  : riscv64-linux-gnu-gcc
    mips     : mips-linux-gnu-gcc

EOF
}

# 检查依赖
check_dependencies() {
    log_info "检查构建依赖..."
    
    # 检查基本工具
    for tool in make pkg-config; do
        if ! command -v $tool >/dev/null 2>&1; then
            log_error "缺少必要工具: $tool"
            return 1
        fi
    done
    
    # 检查交叉编译器
    if [ "$TARGET_ARCH" != "native" ]; then
        local cross_prefix
        case $TARGET_ARCH in
            arm)     cross_prefix="arm-linux-gnueabihf" ;;
            aarch64) cross_prefix="aarch64-linux-gnu" ;;
            riscv64) cross_prefix="riscv64-linux-gnu" ;;
            mips)    cross_prefix="mips-linux-gnu" ;;
            *)       log_error "不支持的架构: $TARGET_ARCH"; return 1 ;;
        esac
        
        if ! command -v "${cross_prefix}-gcc" >/dev/null 2>&1; then
            log_error "缺少交叉编译器: ${cross_prefix}-gcc"
            log_info "安装方法 (Ubuntu/Debian):"
            case $TARGET_ARCH in
                arm)     echo "  sudo apt-get install gcc-arm-linux-gnueabihf" ;;
                aarch64) echo "  sudo apt-get install gcc-aarch64-linux-gnu" ;;
                riscv64) echo "  sudo apt-get install gcc-riscv64-linux-gnu" ;;
                mips)    echo "  sudo apt-get install gcc-mips-linux-gnu" ;;
            esac
            return 1
        fi
    fi
    
    # 检查libmosquitto (仅限本地编译)
    if [ "$TARGET_ARCH" = "native" ]; then
        if ! pkg-config --exists libmosquitto 2>/dev/null; then
            log_warn "libmosquitto开发库未找到"
            log_info "安装方法: sudo apt-get install libmosquitto-dev"
        fi
    fi
    
    log_info "依赖检查完成"
}

# 清理构建目录
clean_build() {
    log_info "清理构建目录..."
    rm -rf "$BUILD_DIR"
    make -C "$SCRIPT_DIR" clean >/dev/null 2>&1 || true
    log_info "清理完成"
}

# 创建构建目录
prepare_build() {
    log_info "准备构建环境..."
    mkdir -p "$BUILD_DIR"
    
    # 复制源文件到构建目录
    cp "$SCRIPT_DIR"/*.c "$SCRIPT_DIR"/*.h "$SCRIPT_DIR"/Makefile "$BUILD_DIR/"
    
    log_debug "构建目录: $BUILD_DIR"
}

# 执行构建
do_build() {
    log_info "开始构建 (架构: $TARGET_ARCH, 类型: $BUILD_TYPE)..."
    
    cd "$BUILD_DIR"
    
    # 设置Make变量
    local make_vars=""
    
    # 设置交叉编译器
    if [ "$TARGET_ARCH" != "native" ]; then
        case $TARGET_ARCH in
            arm)     make_vars="CROSS_COMPILE=arm-linux-gnueabihf-" ;;
            aarch64) make_vars="CROSS_COMPILE=aarch64-linux-gnu-" ;;
            riscv64) make_vars="CROSS_COMPILE=riscv64-linux-gnu-" ;;
            mips)    make_vars="CROSS_COMPILE=mips-linux-gnu-" ;;
        esac
        make_vars="$make_vars EMBEDDED=1"
    fi
    
    # 设置构建类型
    if [ "$BUILD_TYPE" = "debug" ]; then
        make_vars="$make_vars DEBUG=1"
    fi
    
    # 设置静态链接
    if [ "$STATIC_LINK" = "yes" ]; then
        make_vars="$make_vars STATIC=1"
    fi
    
    # 显示构建命令
    local build_cmd="make $make_vars"
    log_debug "构建命令: $build_cmd"
    
    # 执行构建
    if [ "$VERBOSE" = "yes" ]; then
        eval $build_cmd
    else
        eval $build_cmd >/dev/null
    fi
    
    # 检查构建结果
    if [ -f "mqtt_client" ] || [ -f "mqtt_client_static" ]; then
        log_info "构建成功!"
        
        # 显示文件信息
        local binary="mqtt_client"
        if [ "$STATIC_LINK" = "yes" ]; then
            binary="mqtt_client_static"
        fi
        
        if [ -f "$binary" ]; then
            local size=$(du -h "$binary" | cut -f1)
            log_info "二进制文件: $BUILD_DIR/$binary (大小: $size)"
            
            # 显示架构信息
            if command -v file >/dev/null 2>&1; then
                local arch_info=$(file "$binary" | cut -d: -f2)
                log_debug "架构信息:$arch_info"
            fi
        fi
    else
        log_error "构建失败"
        return 1
    fi
}

# 创建部署包
create_package() {
    log_info "创建部署包..."
    
    local package_name="mqtt_client_${TARGET_ARCH}_${BUILD_TYPE}"
    if [ "$STATIC_LINK" = "yes" ]; then
        package_name="${package_name}_static"
    fi
    
    local package_dir="$BUILD_DIR/$package_name"
    mkdir -p "$package_dir"
    
    # 复制二进制文件
    local binary="mqtt_client"
    if [ "$STATIC_LINK" = "yes" ]; then
        binary="mqtt_client_static"
    fi
    
    if [ -f "$BUILD_DIR/$binary" ]; then
        cp "$BUILD_DIR/$binary" "$package_dir/"
        
        # 如果是交叉编译，去除符号表
        if [ "$TARGET_ARCH" != "native" ] && [ "$BUILD_TYPE" = "release" ]; then
            case $TARGET_ARCH in
                arm)     arm-linux-gnueabihf-strip "$package_dir/$binary" 2>/dev/null || true ;;
                aarch64) aarch64-linux-gnu-strip "$package_dir/$binary" 2>/dev/null || true ;;
                riscv64) riscv64-linux-gnu-strip "$package_dir/$binary" 2>/dev/null || true ;;
                mips)    mips-linux-gnu-strip "$package_dir/$binary" 2>/dev/null || true ;;
            esac
        fi
    fi
    
    # 复制配置文件
    cp "$SCRIPT_DIR"/*.h "$package_dir/"
    
    # 创建README
    cat > "$package_dir/README.txt" << EOF
MQTT客户端程序

架构: $TARGET_ARCH
构建类型: $BUILD_TYPE
静态链接: $STATIC_LINK
构建时间: $(date)

使用方法:
1. 确保目标设备已安装libmosquitto库 (如果非静态链接)
2. 运行: ./$binary

配置:
- 修改mqtt_config.h中的MQTT_BROKER_HOST设置代理服务器地址
- 根据需要调整其他配置参数

测试:
mosquitto_pub -h broker.hivemq.com -t "device/command" -m "status"
mosquitto_sub -h broker.hivemq.com -t "device/+"
EOF
    
    # 创建压缩包
    cd "$BUILD_DIR"
    tar -czf "${package_name}.tar.gz" "$package_name"
    
    log_info "部署包已创建: $BUILD_DIR/${package_name}.tar.gz"
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -a|--arch)
            TARGET_ARCH="$2"
            shift 2
            ;;
        -t|--type)
            BUILD_TYPE="$2"
            shift 2
            ;;
        -s|--static)
            STATIC_LINK="yes"
            shift
            ;;
        -v|--verbose)
            VERBOSE="yes"
            shift
            ;;
        -c|--clean)
            clean_build
            exit 0
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            log_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
done

# 验证参数
case $TARGET_ARCH in
    native|arm|aarch64|riscv64|mips) ;;
    *) log_error "不支持的架构: $TARGET_ARCH"; exit 1 ;;
esac

case $BUILD_TYPE in
    debug|release) ;;
    *) log_error "不支持的构建类型: $BUILD_TYPE"; exit 1 ;;
esac

# 主流程
main() {
    log_info "MQTT客户端构建脚本启动"
    
    check_dependencies
    prepare_build
    do_build
    create_package
    
    log_info "构建完成!"
}

# 执行主流程
main